#include <QMessageBox>

#include <QStandardItem>
#include <QDebug>
#include <QtConcurrent/QtConcurrent>
#include <QVBoxLayout>
#include <QProgressBar>
#include <QHeaderView>
#include <QSqlQueryModel>
#include <QSqlRecord>

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dateeditdelegate.h"
#include "lineeditdelegate.h"

#include "addexpenddialog.h"
#include "newexpensedialog.h"
using namespace QtConcurrent;

#define MAX_RATE 10
#define STEP_RATE 2.0
#define SALARY_RATE_DEFAULT 8
#define CASH_RATE_DEFAULT 10
#define WORKING_DEFAULT true

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    Initialize();
}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::Initialize()
{
    int numTasks = 7;
    int step = 0;
    QProgressDialog progress("Initialize...", "Cancel", 0, numTasks, this);
    progress.setWindowModality(Qt::WindowModal);
    progress.show();

    progress.setValue(step);
    //QThread::sleep(1);
    database = new Databasehelper();
    if (database->openConnection() == true){
        qDebug() << "Connect to database OK";
    }else{
        qDebug() << "Connect to database FAILED";

    }
    progress.setValue(step + 1);

    QDate today = QDate::currentDate();

    this->ui->dateEditIncome->setDate(today);
    this->ui->dateEditSalonIncome->setDate(today);
    this->ui->dateEditPayroll->setDate(database->getLastPaidDate());
    this->ui->dateEditPayroll->setReadOnly(true);
    this->mAddExpDlg = NULL;

    mItemModelSalonIncome = new QStandardItemModel();
    mItemModelEmployeeIncome = new QStandardItemModel();
    mItemModelPayroll = new QStandardItemModel();

    QObject::connect(this->mItemModelSalonIncome, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(itemModelSalonIncomeDataChanged(QModelIndex,QModelIndex)));
    QObject::connect(this->mItemModelEmployeeIncome, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(itemModelEmployeeIncomeDataChanged(QModelIndex,QModelIndex)));
    QObject::connect(ui->dateEditIncome, SIGNAL(dateChanged(QDate)), this, SLOT(dateEditIncomeChanged(QDate)));
    QObject::connect(ui->dateEditSalonIncome, SIGNAL(dateChanged(QDate)), this, SLOT(dateEditSalonIncomeChanged(QDate)));
    QObject::connect(ui->pushButtonUpdateEmployeeIncome, SIGNAL(clicked()), this, SLOT(pushButtonUpdateEmployeeIncomeClicked()));
    QObject::connect(ui->pushButtonUpdateSalonIncome, SIGNAL(clicked()), this, SLOT(pushButtonUpdateSalonIncomeClicked()));

    QObject::connect(ui->salaryRateSlider, SIGNAL(valueChanged(int)), this, SLOT(salaryRateSliderValueChanged(int)));
    QObject::connect(ui->cashRateSlider, SIGNAL(valueChanged(int)), this, SLOT(cashRateSliderValueChanged(int)));
    QObject::connect(ui->resetEmployeeFieldButton, SIGNAL(clicked()), this, SLOT(resetEmployeeFieldButtonClicked()));
    QObject::connect(ui->pushButtonUpdateEmployee, SIGNAL(clicked()), this, SLOT(pushButtonUpdateEmployeeCliked()));
    QObject::connect(ui->tableViewEmployeeList, SIGNAL(clicked(const QModelIndex &)), this, SLOT(tableViewEmployeeListClicked(const QModelIndex &)));
    QObject::connect(ui->pushButtonUpdatePayroll, SIGNAL(clicked()), this, SLOT(pushButtonUpdatePayrollClicked()));

    progress.setValue(step + 2);


    loadEmployeeList();
    QDate dateIncome = this->ui->dateEditIncome->date();
    progress.setValue(step + 3);

    loadEmployeeIncome(dateIncome);
    progress.setValue(step + 4);

    loadSalonIncome(dateIncome);
    progress.setValue(step + 5);

    loadpayroll(database->getLastPaidDate());
    progress.setValue(numTasks);

}

void MainWindow::salaryRateSliderValueChanged(int value)
{
    ui->ownerValue->setText(QString::number(value / STEP_RATE));
    ui->EmployeeValue->setText(QString::number(MAX_RATE -(value / STEP_RATE)));
}

void MainWindow::cashRateSliderValueChanged(int value)
{
    ui->cashValue->setText(QString::number(value / STEP_RATE));
    ui->chequeValue->setText(QString::number(MAX_RATE -(value / STEP_RATE)));
}

void MainWindow::resetEmployeeFieldButtonClicked()
{
    clearEmployeeField();
}

void MainWindow::pushButtonUpdateEmployeeCliked()
{
    QString employeeName = ui->lineEditEmployeeName->text();
    QString employeePhone = ui->lineEditPhone->text();
    if ((employeeName.length() < 3) || (employeePhone.length() < 10)){
        QMessageBox::information( this, "Warning", "Name have least 3 characters and phone number have least 10 characters." );
    }else{
        int employeeSalaryRate = MAX_RATE - (ui->salaryRateSlider->value() / 2);
        int employeeCashRate = ui->cashRateSlider->value() / 2.0;
        int employeeWorking = ui->checkBoxWorking->isChecked() ? 1:0;

        Employee *newEmployee = new Employee();
        newEmployee->setCashRate(employeeCashRate);
        newEmployee->setName(employeeName);
        newEmployee->setPhone(employeePhone);
        newEmployee->setSalaryRate(employeeSalaryRate);
        newEmployee->setWorkingStatus(employeeWorking);
        if (this->database->createEmployee(newEmployee)){
            QMessageBox msgBox;
            msgBox.addButton(QMessageBox::Yes);
            msgBox.addButton(QMessageBox::No);
            msgBox.setText("This person is already in the database. Do you update data?");

            int selection = msgBox.exec();
            if(selection == QMessageBox::Yes)
            {
              database->updateEmployee(newEmployee);
            }
            else if(selection == QMessageBox::No)
            {
              qDebug() << "no";
            }
        }else{
            QMessageBox::information( this, "Infomation", "Successfully." );
        }
        delete newEmployee;
    }
    clearEmployeeField();
    loadEmployeeList();
    loadEmployeeIncome(this->ui->dateEditIncome->date());
}

void MainWindow::dateEditIncomeChanged(QDate date)
{
    this->ui->dateEditSalonIncome->setDate(date);
    loadSalonIncome(date);
    loadEmployeeIncome(date);
}

void MainWindow::pushButtonUpdateEmployeeIncomeClicked()
{
    QProgressDialog* progressDialog = new QProgressDialog("Processing...", "Abort", 0, INT_MAX, this);

    QProgressBar* bar = new QProgressBar(progressDialog);
    bar->setRange(0, this->mItemModelEmployeeIncome->rowCount() - 1);
    bar->setValue(0);
    progressDialog->setBar(bar);

    progressDialog->setMinimumWidth(350);
    progressDialog->setMinimumDuration(1000);
    progressDialog->setWindowModality(Qt::WindowModal);
    progressDialog->setValue(0);


    progressDialog->show();
    progressDialog->setWindowModality(Qt::WindowModal);
    database->updateEmployeeIncomes(this->mItemModelEmployeeIncome, progressDialog);

    progressDialog->close();

    //update salon income
    QProgressDialog* progressDialogSalonIncome = new QProgressDialog("Processing...", "Abort", 0, INT_MAX, this);

    QProgressBar* barSalonIncome = new QProgressBar(progressDialogSalonIncome);
    barSalonIncome->setRange(0, this->mItemModelSalonIncome->rowCount());
    barSalonIncome->setValue(0);
    progressDialogSalonIncome->setBar(barSalonIncome);

    progressDialogSalonIncome->setMinimumWidth(350);
    progressDialogSalonIncome->setMinimumDuration(1000);
    progressDialogSalonIncome->setWindowModality(Qt::WindowModal);
    progressDialogSalonIncome->setValue(0);


    progressDialogSalonIncome->show();
    progressDialogSalonIncome->setWindowModality(Qt::WindowModal);

    database->updateSalonIncomes(this->mItemModelSalonIncome, this->ui->textEditSalonIncomeNote->toPlainText(), progressDialog);

    progressDialogSalonIncome->close();

    QMessageBox::information( this, "Infomation", "Successfully." );
}

void MainWindow::dateEditSalonIncomeChanged(QDate Q)
{
    dateEditIncomeChanged(Q);
}

void MainWindow::pushButtonUpdateSalonIncomeClicked()
{
    pushButtonUpdateEmployeeIncomeClicked();
}

void MainWindow::itemModelSalonIncomeDataChanged(QModelIndex index1, QModelIndex)
{
    QModelIndex indexCash;
    QModelIndex indexCredit;
    QModelIndex indexTotal;
    QModelIndex indexGiftCardOut;
    QModelIndex indexGiftCardIn;

    double cash = 0;

    if ((index1.column() == SalonIncome::CREDIT_COL) ||  (index1.column() == SalonIncome::GIFT_CARD_IN)
            || (index1.column() == SalonIncome::GIFT_CARD_OUT)){
        QString salary = this->mItemModelSalonIncome->data(index1).toString();
        if ( salary.indexOf('.') == -1){
            mItemModelSalonIncome->setData(index1,QString::number(salary.toDouble() / 100.00, 'f', 2));

        }else if (salary.indexOf('.') == (salary.length() - 2)){
            mItemModelSalonIncome->setData(index1,QString::number(salary.toDouble(), 'f', 2));

        }

    }

    indexCash = this->mItemModelSalonIncome->index(index1.row(),SalonIncome::CASH_COL);
    indexCredit = this->mItemModelSalonIncome->index(index1.row(),SalonIncome::CREDIT_COL);
    indexTotal = this->mItemModelSalonIncome->index(index1.row(),SalonIncome::TOTAL_COL);
    indexGiftCardIn =  this->mItemModelSalonIncome->index(index1.row(),SalonIncome::GIFT_CARD_IN);
    indexGiftCardOut =  this->mItemModelSalonIncome->index(index1.row(),SalonIncome::GIFT_CARD_OUT);

//    total = this->mItemModelSalonIncome->data(indexCash).toDouble()
//            + this->mItemModelSalonIncome->data(indexCredit).toDouble()
//            - this->mItemModelSalonIncome->data(indexGiftCardIn).toDouble()
//            + this->mItemModelSalonIncome->data(indexGiftCardOut).toDouble();

    cash =  this->mItemModelSalonIncome->data(indexTotal).toDouble()
            - this->mItemModelSalonIncome->data(indexCredit).toDouble()
            - this->mItemModelSalonIncome->data(indexGiftCardIn).toDouble()
            + this->mItemModelSalonIncome->data(indexGiftCardOut).toDouble();
    this->mItemModelSalonIncome->setData(indexCash, QString::number(cash, 'f',2));
}

void MainWindow::itemModelEmployeeIncomeDataChanged(QModelIndex index1, QModelIndex)
{
    QModelIndex indexTotalSalary = mItemModelEmployeeIncome->index(mItemModelEmployeeIncome->rowCount() - 1, EmployeeIncome::SALARY_COL, QModelIndex());
    QModelIndex indexTotalTip = mItemModelEmployeeIncome->index(mItemModelEmployeeIncome->rowCount() - 1, EmployeeIncome::TIP_COL, QModelIndex());


    double totalSalary = 0;
    double totalTip = 0;

    if ((index1.column() == EmployeeIncome::SALARY_COL) || (index1.column() == EmployeeIncome::TIP_COL)){
        QString salary = this->mItemModelEmployeeIncome->data(index1).toString();
        if ( salary.indexOf('.') == -1){
            mItemModelEmployeeIncome->setData(index1,QString::number(salary.toDouble() / 100.00, 'f', 2));

        }else if (salary.indexOf('.') == (salary.length() - 2)){
            mItemModelEmployeeIncome->setData(index1,QString::number(salary.toDouble(), 'f', 2));

        }

    }
    for (int row = 0; row < (mItemModelEmployeeIncome->rowCount() - 1); row++)
    {
        QModelIndex indexRow = mItemModelEmployeeIncome->index(row, EmployeeIncome::SALARY_COL);
        totalSalary += mItemModelEmployeeIncome->data(indexRow).toDouble();

        indexRow = mItemModelEmployeeIncome->index(row, EmployeeIncome::TIP_COL);
        totalTip += mItemModelEmployeeIncome->data(indexRow).toDouble();

    }

    mItemModelEmployeeIncome->setData(indexTotalSalary, QVariant(QString::number(totalSalary,'f',2)), Qt::AlignRight);
    mItemModelEmployeeIncome->setData(indexTotalTip, QVariant(QString::number(totalTip,'f',2)), Qt::AlignRight);
    QModelIndex indexTotalSalonIncome = mItemModelSalonIncome->index(0, SalonIncome::TOTAL_COL);
    mItemModelSalonIncome->setData(indexTotalSalonIncome, QString::number(totalSalary + totalTip, 'f', 2));
}

void MainWindow::dateEditPayRollChanged(QDate)
{

}

void MainWindow::pushButtonUpdatePayrollClicked()
{
    QProgressDialog* progressDialog = new QProgressDialog("Processing...", "Abort", 0, INT_MAX, this);

    QProgressBar* bar = new QProgressBar(progressDialog);
    bar->setRange(0, this->mItemModelPayroll->rowCount() - 1);
    bar->setValue(0);
    progressDialog->setBar(bar);

    progressDialog->setMinimumWidth(350);
    progressDialog->setMinimumDuration(1000);
    progressDialog->setWindowModality(Qt::WindowModal);
    progressDialog->setValue(0);


    progressDialog->show();
    progressDialog->setWindowModality(Qt::WindowModal);
    database->updatePayroll(this->mItemModelPayroll, progressDialog);
    progressDialog->setValue(this->mItemModelPayroll->rowCount());
    progressDialog->close();

    QMessageBox::information( this, "Infomation", "Successfully." );
    loadpayroll(this->ui->dateEditPayroll->date());
}

void MainWindow::tableViewEmployeeListClicked(const QModelIndex &index){

    QVariant value = ui->tableViewEmployeeList->model()->data(index,0);
    QString employeeName = value.toString();
    QLinkedList<Employee*> *employeelist;
    employeelist = database->selectEmployee(" where name='" + employeeName + "'");

    Employee* employee;

    while(!employeelist->isEmpty())
    {
       employee = employeelist->takeFirst();

       this->ui->lineEditEmployeeName->setText(employee->getName());
       this->ui->lineEditPhone->setText(employee->getPhone());
       this->ui->salaryRateSlider->setValue((MAX_RATE - employee->getSalaryRate()) * 2);
       this->ui->cashRateSlider->setValue(employee->getCashRate() * 2);
       this->ui->checkBoxWorking->setChecked(bool (employee->getWorkingStatus()));
    }


}

void MainWindow::clearEmployeeField(){
    ui->lineEditEmployeeName->setText("");
    ui->lineEditPhone->setText("");
    ui->salaryRateSlider->setValue(SALARY_RATE_DEFAULT);
    ui->cashRateSlider->setValue(CASH_RATE_DEFAULT);
    ui->checkBoxWorking->setChecked(WORKING_DEFAULT);
}
void  MainWindow::loadEmployeeList(){
    QLinkedList<Employee*> *employeeList = new QLinkedList<Employee*>();
    employeeList = database->selectEmployee("");

    mItemModelEmployee = new QStandardItemModel(employeeList->count() + 5,4,this); //2 Rows and 3 Columns
    mItemModelEmployee->clear();
    mItemModelEmployee->setHorizontalHeaderItem(0, new QStandardItem(QString("Name")));
    mItemModelEmployee->setHorizontalHeaderItem(1, new QStandardItem(QString("Phone")));
    mItemModelEmployee->setHorizontalHeaderItem(2, new QStandardItem(QString("Paid Date")));
    mItemModelEmployee->setHorizontalHeaderItem(3, new QStandardItem(QString("Working")));
    mItemModelEmployee->setHorizontalHeaderItem(4, new QStandardItem(QString("Salary rate")));
    mItemModelEmployee->setHorizontalHeaderItem(5, new QStandardItem(QString("Cash rate")));
    mItemModelEmployee->setHorizontalHeaderItem(6, new QStandardItem(QString("Updated date")));

    ui->tableViewEmployeeList->setModel(mItemModelEmployee);

    int rowEmployeeTable = 0;
    Employee* employee_query;

    while(!employeeList->isEmpty())
    {
        employee_query = employeeList->takeFirst();
        mItemModelEmployee->setItem(rowEmployeeTable, 0, new QStandardItem(employee_query->getName()));
        mItemModelEmployee->setItem(rowEmployeeTable, 1, new QStandardItem(employee_query->getPhone()));
        mItemModelEmployee->setItem(rowEmployeeTable, 2, new QStandardItem(employee_query->getPaidAt().toString("MM-dd-yyyy")));
        mItemModelEmployee->setItem(rowEmployeeTable, 3, new QStandardItem((employee_query->getWorkingStatus() == 1)?"Active":"Deactive"));
        mItemModelEmployee->setItem(rowEmployeeTable, 4, new QStandardItem(QString::number(employee_query->getSalaryRate())+ "/10"));
        mItemModelEmployee->setItem(rowEmployeeTable, 5, new QStandardItem(QString::number(employee_query->getCashRate())+ "/10"));
        mItemModelEmployee->setItem(rowEmployeeTable, 6, new QStandardItem(employee_query->getModifiedAt().toString("MM-dd-yyyy")));
        rowEmployeeTable++;
    }
    delete employeeList;
}

void MainWindow::loadEmployeeIncome(QDate dateIncome)
{
    QLinkedList<EmployeeIncome *> *employeeIncomesList = database->selectEmployeeIncomes(dateIncome);

    mItemModelEmployeeIncome->clear();
    mItemModelEmployeeIncome->setColumnCount(5);
    mItemModelEmployeeIncome->setRowCount(employeeIncomesList->size() + 1);
    mItemModelEmployeeIncome->setHorizontalHeaderItem(EmployeeIncome::ID_COL, new QStandardItem(QString("ID")));
    mItemModelEmployeeIncome->setHorizontalHeaderItem(EmployeeIncome::NAME_COL, new QStandardItem(QString("Name")));
    mItemModelEmployeeIncome->setHorizontalHeaderItem(EmployeeIncome::DATE_COL, new QStandardItem(QString("Date")));
    mItemModelEmployeeIncome->setHorizontalHeaderItem(EmployeeIncome::SALARY_COL, new QStandardItem(QString("Income")));
    mItemModelEmployeeIncome->setHorizontalHeaderItem(EmployeeIncome::TIP_COL, new QStandardItem(QString("Tip")));

    ui->tableViewEmployeeIncome->setModel(mItemModelEmployeeIncome);

    int rowEmployeeTable = 0;
    //ui->tableViewEmployeeIncome->setItemDelegateForColumn(1, new DateEditDelegate);
    ui->tableViewEmployeeIncome->setItemDelegateForColumn(EmployeeIncome::SALARY_COL, new LineEditDelegate);
    ui->tableViewEmployeeIncome->setItemDelegateForColumn(EmployeeIncome::TIP_COL, new LineEditDelegate);
    double salaryTotal = 0;
    double tipTotal = 0;
    EmployeeIncome* empl_income;
    while(!employeeIncomesList->isEmpty())
    {
        empl_income = employeeIncomesList->takeFirst();
        QStandardItem *itemEmployeeID = new QStandardItem(QString::number(empl_income->getEmployeeId()));
        itemEmployeeID->setEditable(false);
        mItemModelEmployeeIncome->setItem(rowEmployeeTable, EmployeeIncome::ID_COL , itemEmployeeID);

        QStandardItem *itemNameIncome = new QStandardItem(empl_income->getName());
        itemNameIncome->setEditable(false);
        mItemModelEmployeeIncome->setItem(rowEmployeeTable, EmployeeIncome::NAME_COL, itemNameIncome);


        QStandardItem *itemDateIncome = new QStandardItem(dateIncome.toString("MM-dd-yyyy"));
        itemDateIncome->setEditable(false);
        mItemModelEmployeeIncome->setItem(rowEmployeeTable, EmployeeIncome::DATE_COL, itemDateIncome);

        QModelIndex index = mItemModelEmployeeIncome->index(rowEmployeeTable, EmployeeIncome::SALARY_COL, QModelIndex());
        mItemModelEmployeeIncome->setData(index, QVariant(QString::number(empl_income->getSalary(), 'd', 2)), Qt::AlignRight);
        salaryTotal += empl_income->getSalary();

        index = mItemModelEmployeeIncome->index(rowEmployeeTable, EmployeeIncome::TIP_COL, QModelIndex());
        mItemModelEmployeeIncome->setData(index, QVariant(QString::number(empl_income->getTip(), 'f', 2)), Qt::AlignRight);
        tipTotal += empl_income->getTip();
        rowEmployeeTable++;

    }
    QStandardItem *itemIdTotalText= new QStandardItem("Total");

    mItemModelEmployeeIncome->setItem(rowEmployeeTable, EmployeeIncome::DATE_COL , itemIdTotalText);

    QModelIndex index = mItemModelEmployeeIncome->index(rowEmployeeTable, EmployeeIncome::SALARY_COL, QModelIndex());
    mItemModelEmployeeIncome->setData(index, QVariant(QString::number(salaryTotal,'f',2)), Qt::AlignRight);

    index = mItemModelEmployeeIncome->index(rowEmployeeTable, EmployeeIncome::TIP_COL, QModelIndex());
    mItemModelEmployeeIncome->setData(index, QVariant(QString::number(tipTotal,'f',2)), Qt::AlignRight);


    ui->tableViewEmployeeIncome->hideColumn(EmployeeIncome::ID_COL);
}

void MainWindow::loadSalonIncome(QDate dateIncome)
{
    bool addRecord = true;
    QSqlQueryModel *model = new QSqlQueryModel;
    QString query_str = "SELECT * FROM salon_incomes WHERE created_at ='" + dateIncome.toString("yyyy-MM-dd") + "'";
    qDebug() << query_str;
    model->setQuery(query_str);

    this->ui->textEditSalonIncomeNote->clear();
    mItemModelSalonIncome->clear();
    mItemModelSalonIncome->setColumnCount(7);
    mItemModelSalonIncome->setRowCount(model->rowCount());

    mItemModelSalonIncome->setHorizontalHeaderItem(SalonIncome::ID_COL, new QStandardItem(QString("ID")));
    mItemModelSalonIncome->setHorizontalHeaderItem(SalonIncome::CASH_COL, new QStandardItem(QString("Cash")));
    mItemModelSalonIncome->setHorizontalHeaderItem(SalonIncome::CREDIT_COL, new QStandardItem(QString("Credit")));
    mItemModelSalonIncome->setHorizontalHeaderItem(SalonIncome::GIFT_CARD_IN, new QStandardItem(QString("Gift card in")));
    mItemModelSalonIncome->setHorizontalHeaderItem(SalonIncome::GIFT_CARD_OUT, new QStandardItem(QString("Gift card out")));

    mItemModelSalonIncome->setHorizontalHeaderItem(SalonIncome::TOTAL_COL, new QStandardItem(QString("Total")));
    mItemModelSalonIncome->setHorizontalHeaderItem(SalonIncome::CREATEDDATE_COL, new QStandardItem(QString("Date")));

    ui->tableViewSalonIncome->setModel(mItemModelSalonIncome);

    int rowWorkerTable = 0;

    ui->tableViewSalonIncome->setItemDelegateForColumn(SalonIncome::CASH_COL, new LineEditDelegate);
    ui->tableViewSalonIncome->setItemDelegateForColumn(SalonIncome::CREDIT_COL, new LineEditDelegate);
    ui->tableViewSalonIncome->setItemDelegateForColumn(SalonIncome::GIFT_CARD_IN, new LineEditDelegate);
    ui->tableViewSalonIncome->setItemDelegateForColumn(SalonIncome::GIFT_CARD_OUT, new LineEditDelegate);

    if (model->rowCount() > 0){
        for (rowWorkerTable =0; rowWorkerTable < model->rowCount(); rowWorkerTable++)
        {

            QStandardItem *itemIdIncome = new QStandardItem(QString::number((model->record(rowWorkerTable).value("id")).toInt()));
            itemIdIncome->setEditable(false);
            mItemModelSalonIncome->setItem(rowWorkerTable, SalonIncome::ID_COL , itemIdIncome);

            QStandardItem *itemCashIncome = new QStandardItem(model->record(rowWorkerTable).value("cash").toDouble());
            itemCashIncome->setEditable(false);
            itemCashIncome->setData(QVariant(Qt::AlignRight | Qt::AlignCenter), Qt::TextAlignmentRole);
            mItemModelSalonIncome->setItem(rowWorkerTable, SalonIncome::CASH_COL, itemCashIncome);


            QModelIndex index = mItemModelSalonIncome->index(rowWorkerTable, SalonIncome::CREDIT_COL, QModelIndex());
            mItemModelSalonIncome->setData(index, QVariant(QString::number(model->record(rowWorkerTable).value("credit").toDouble(), 'f', 2)), Qt::AlignRight);

            index = mItemModelSalonIncome->index(rowWorkerTable, SalonIncome::GIFT_CARD_IN, QModelIndex());
            mItemModelSalonIncome->setData(index, QVariant(QString::number(model->record(rowWorkerTable).value("gift_in").toDouble(), 'f', 2)), Qt::AlignRight);


            index = mItemModelSalonIncome->index(rowWorkerTable, SalonIncome::GIFT_CARD_OUT, QModelIndex());
            mItemModelSalonIncome->setData(index, QVariant(QString::number(model->record(rowWorkerTable).value("gift_out").toDouble(), 'f', 2)), Qt::AlignRight);

            QStandardItem *itemTotalIncome = new QStandardItem((model->record(rowWorkerTable).value("total")).toString());
            itemTotalIncome->setEditable(false);
            itemTotalIncome->setData(QVariant(Qt::AlignRight | Qt::AlignCenter), Qt::TextAlignmentRole);
            mItemModelSalonIncome->setItem(rowWorkerTable, SalonIncome::TOTAL_COL, itemTotalIncome);

            QDate tempDate = model->record(rowWorkerTable).value("created_at").toDate();
            if ((tempDate.day() == dateIncome.day()) && (tempDate.month() == dateIncome.month()) && (tempDate.year() == dateIncome.year())){
                addRecord = false;
            }
            QStandardItem *itemDateIncome = new QStandardItem(tempDate.toString("MM-dd-yyyy"));
            itemDateIncome->setEditable(false);
            mItemModelSalonIncome->setItem(rowWorkerTable, SalonIncome::CREATEDDATE_COL, itemDateIncome);

            this->ui->textEditSalonIncomeNote->setText(model->record(rowWorkerTable).value("note").toString());

         }
    }
    // add new blank record
    if (addRecord){
        QStandardItem *itemIdIncome = new QStandardItem();
        itemIdIncome->setEditable(false);
        mItemModelSalonIncome->setItem(rowWorkerTable, SalonIncome::ID_COL , itemIdIncome);

        QModelIndex index = mItemModelSalonIncome->index(rowWorkerTable, SalonIncome::CASH_COL, QModelIndex());
        mItemModelSalonIncome->setData(index, QVariant(QString::number(0,'f',2)), Qt::AlignRight);

        index = mItemModelSalonIncome->index(rowWorkerTable, SalonIncome::CREDIT_COL, QModelIndex());
        mItemModelSalonIncome->setData(index, QVariant(QString::number(0,'f',2)), Qt::AlignRight);

        index = mItemModelSalonIncome->index(rowWorkerTable, SalonIncome::GIFT_CARD_IN, QModelIndex());
        mItemModelSalonIncome->setData(index, QVariant(QString::number(0,'f',2)), Qt::AlignRight);

        index = mItemModelSalonIncome->index(rowWorkerTable, SalonIncome::GIFT_CARD_OUT, QModelIndex());
        mItemModelSalonIncome->setData(index, QVariant(QString::number(0,'f',2)), Qt::AlignRight);

        QStandardItem *itemTotalIncome = new QStandardItem();
        itemTotalIncome->setEditable(false);
        itemTotalIncome->setData(QVariant(Qt::AlignRight | Qt::AlignCenter), Qt::TextAlignmentRole);
        mItemModelSalonIncome->setItem(rowWorkerTable, SalonIncome::TOTAL_COL, itemTotalIncome);

        QStandardItem *itemDateIncome = new QStandardItem(dateIncome.toString("MM-dd-yyyy"));
        itemDateIncome->setEditable(false);
        mItemModelSalonIncome->setItem(rowWorkerTable, SalonIncome::CREATEDDATE_COL, itemDateIncome);
    }

    ui->tableViewSalonIncome->hideColumn(SalonIncome::ID_COL);
}

void MainWindow::loadpayroll(QDate)
{
    QSqlQueryModel *model = new QSqlQueryModel;
    QString query_str = "SELECT * FROM payroll_view where salary > 0";

    const int TOTAL_COL = 13;
    const int CHECK_TIP_COL = 12;

    qDebug() << query_str;
    model->setQuery(query_str);
    mItemModelPayroll->clear();
    mItemModelPayroll->setColumnCount(13);
    mItemModelPayroll->setRowCount(model->rowCount());

    mItemModelPayroll->setHorizontalHeaderItem(SalaryExpend::ID_COL, new QStandardItem(QString("ID")));
    mItemModelPayroll->setHorizontalHeaderItem(SalaryExpend::EMPLOYEE_ID_COL, new QStandardItem(QString("Employee ID")));
    mItemModelPayroll->setHorizontalHeaderItem(SalaryExpend::EMPLOYEE_NAME_COL, new QStandardItem(QString("Name")));

    mItemModelPayroll->setHorizontalHeaderItem(SalaryExpend::SALARY_RATE_COL, new QStandardItem(QString("Salary rate")));
    mItemModelPayroll->setHorizontalHeaderItem(SalaryExpend::CASH_RATE_COL, new QStandardItem(QString("Cash rate")));
    mItemModelPayroll->setHorizontalHeaderItem(SalaryExpend::FROM_AT_COL, new QStandardItem(QString("From date")));
    mItemModelPayroll->setHorizontalHeaderItem(SalaryExpend::TO_AT_COL, new QStandardItem(QString("To date")));
    mItemModelPayroll->setHorizontalHeaderItem(SalaryExpend::CREATED_AT_COL, new QStandardItem(QString("Paid Date")));

    mItemModelPayroll->setHorizontalHeaderItem(SalaryExpend::CASH_COL, new QStandardItem(QString("Cash")));
    mItemModelPayroll->setHorizontalHeaderItem(SalaryExpend::CHECK_COL, new QStandardItem(QString("Check")));
    mItemModelPayroll->setHorizontalHeaderItem(SalaryExpend::TIP_COL, new QStandardItem(QString("Tip")));
    mItemModelPayroll->setHorizontalHeaderItem(CHECK_TIP_COL, new QStandardItem(QString("Check + Tip")));
    mItemModelPayroll->setHorizontalHeaderItem(TOTAL_COL, new QStandardItem(QString("Total")));
    ui->tableViewPaidToEmployee->setModel(mItemModelPayroll);
    int rowPayrollable = 0;
    double totalCash = 0;
    double totalCheck = 0;

    qDebug()<< model->rowCount();
    for (rowPayrollable =0; rowPayrollable < model->rowCount(); rowPayrollable++)
    {


        QStandardItem *itemIdSalary = new QStandardItem(QString::number((model->record(rowPayrollable).value("id")).toInt()));
        itemIdSalary->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, SalaryExpend::ID_COL , itemIdSalary);

        QStandardItem *itemEmployeeIdSalary = new QStandardItem(QString::number((model->record(rowPayrollable).value("employee_id")).toInt()));
        itemEmployeeIdSalary->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, SalaryExpend::EMPLOYEE_ID_COL , itemEmployeeIdSalary);


        QStandardItem *itemEmployeeNameSalary = new QStandardItem(model->record(rowPayrollable).value("name").toString());
        itemEmployeeNameSalary->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, SalaryExpend::EMPLOYEE_NAME_COL , itemEmployeeNameSalary);

        double salaryRate = 0;
        double cashRate= 0;
        double salary = 0;
        double cash = 0;
        double check = 0;
        double tip = 0;


        QDate fromDate, toDate, today;
        salaryRate = model->record(rowPayrollable).value("salary_rate").toDouble();
        cashRate = model->record(rowPayrollable).value("cash_rate").toDouble();
        fromDate = model->record(rowPayrollable).value("start_at").toDate().addDays(1);

        QStandardItem *itemSalaryRate = new QStandardItem(QString::number(salaryRate));
        itemSalaryRate->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, SalaryExpend::SALARY_RATE_COL , itemSalaryRate);

        QStandardItem *itemCashRate = new QStandardItem(QString::number(cashRate));
        itemCashRate->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, SalaryExpend::CASH_RATE_COL , itemCashRate);

        QStandardItem *itemFromDate = new QStandardItem(fromDate.toString("MM-dd-yyyy"));
        itemFromDate->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, SalaryExpend::FROM_AT_COL , itemFromDate);

        toDate = model->record(rowPayrollable).value("end_at").toDate();
        QStandardItem *itemToDate = new QStandardItem(toDate.toString("MM-dd-yyyy"));
        itemToDate->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, SalaryExpend::TO_AT_COL , itemToDate);

        today = QDate::currentDate();
        QStandardItem *itemToDay = new QStandardItem(today.toString("MM-dd-yyyy"));
        itemToDay->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, SalaryExpend::CREATED_AT_COL , itemToDay);

        tip = model->record(rowPayrollable).value("tip").toDouble();
        cash = model->record(rowPayrollable).value("cash").toDouble();
        QStandardItem *itemCash = new QStandardItem(QString::number(cash,'f',2));
        itemCash->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, SalaryExpend::CASH_COL , itemCash);

        check = model->record(rowPayrollable).value("check").toDouble();
        QStandardItem *itemCheck = new QStandardItem(QString::number(check,'f',2));
        itemCheck->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, SalaryExpend::CHECK_COL , itemCheck);

        QStandardItem *itemTip = new QStandardItem(QString::number(tip,'f',2));
        itemTip->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, SalaryExpend::TIP_COL , itemTip);

        QStandardItem *itemCheckTip = new QStandardItem(QString::number(tip + check,'f',2));
        itemCheckTip->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, CHECK_TIP_COL , itemCheckTip);

        QStandardItem *itemTotal = new QStandardItem(QString::number(check + cash + tip,'f',2));
        itemTotal->setEditable(false);
        mItemModelPayroll->setItem(rowPayrollable, TOTAL_COL , itemTotal);

     }
     QModelIndex index = mItemModelPayroll->index(rowPayrollable, SalaryExpend::CASH_COL, QModelIndex());
     mItemModelPayroll->setData(index, QVariant(QString::number(totalCash,'f',2)), Qt::AlignRight);

     index = mItemModelPayroll->index(rowPayrollable, SalaryExpend::CHECK_COL, QModelIndex());
     mItemModelPayroll->setData(index, QVariant(QString::number(totalCheck,'f',2)), Qt::AlignRight);

     index = mItemModelPayroll->index(rowPayrollable, TOTAL_COL, QModelIndex());
     mItemModelPayroll->setData(index, QVariant(QString::number(totalCheck + totalCash,'f',2)), Qt::AlignRight);

     ui->tableViewPaidToEmployee->hideColumn(SalaryExpend::ID_COL);
     ui->tableViewPaidToEmployee->hideColumn(SalaryExpend::EMPLOYEE_ID_COL);
     ui->tableViewPaidToEmployee->hideColumn(SalaryExpend::MODIFIED_AT_COL);
     ui->tableViewPaidToEmployee->hideColumn(SalaryExpend::CREATED_AT_COL);
}

void MainWindow::on_pushButtonOtherExpenses_clicked()
{
    if (!this->mAddExpDlg)
    {
        this->mAddExpDlg = new AddExpendDialog(this);
    }
    this->mAddExpDlg->setModal(true);
    this->mAddExpDlg->show();
    this->mAddExpDlg->raise();
    this->mAddExpDlg->activateWindow();

}
AddExpendDialog *MainWindow::getMAddExpDlg() const
{
    return mAddExpDlg;
}

void MainWindow::setMAddExpDlg(AddExpendDialog *value)
{
    mAddExpDlg = value;
}

